// Userlist data array for filling in info box
var userListData = [];

// DOM Ready =============================================================
$(document).ready(function() {
    // Populate the user table on initial page load
    populateTable();
});

// Functions =============================================================
var serverData = null
var tmpl = Handlebars.compile('<tr><td id="{{user_id}}">{{user_id}}</td><td>{{name}}</td>'+
        '<td>{{order_source}}</td><td>{{order_no}}</td><td>{{old_order_count}}</td>'+
        '<td>{{rule_id}}</td><td>{{number}}</td><td>{{day}}</td></tr>');

// Fill table with data
function populateTable(cache) {

    var processTable = function(dataObj){
        console.log('start',new Date());
        var tableData =  $(dataObj).map(function(i,val){
                            return tmpl(val);
                        });
        console.log('end',new Date());
        
        var clusterize = new Clusterize({
            rows: $.makeArray(tableData),
            scrollId: 'scrollArea',
            contentId: 'contentArea'
        });
    }

    if(!serverData){
        $.getJSON( '/orders', function( data ) {
            serverData = data;
            processTable(serverData);
        });
    }else
        processTable(serverData);
    $('ul.nav.navbar-nav.navbar-right  a#save').click(function(){
        var tableData =  $(serverData).map(function(i,val){
                            return val.user_id+','
                                +val.name+','
                                +val.order_source+','
                                +val.order_no+','
                                +val.old_order_count+','
                                +val.rule_id+','
                                +val.number+','
                                +val.day+',';
                            });
        var blob = new Blob([$.makeArray(tableData).join('\n')], {type: "text/csv;charset=utf-8"});
        saveAs(blob, "personal_order.csv");
    })
};